/*
Copyright  2018 Blockchain Technology and Application Joint Lab, Fintech Research Center of ISCAS.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
import React, {Component} from 'react';
import {createContainer} from 'meteor/react-meteor-data';
import {browserHistory} from 'react-router';

import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
import AppBar from 'material-ui/AppBar';
import TextField from 'material-ui/TextField';
import DropDownMenu from 'material-ui/DropDownMenu';
import MenuItem from 'material-ui/MenuItem';
import Dialog from 'material-ui/Dialog';
import Snackbar from 'material-ui/Snackbar';
import Chip from 'material-ui/Chip';
import SvgIconCheck from 'material-ui/svg-icons/toggle/check-box';
import SvgIconErr from 'material-ui/svg-icons/alert/error';
import SvgIconLeftNavi from 'material-ui/svg-icons/navigation/chevron-left';
import Avatar from 'material-ui/Avatar';
import IconButton from 'material-ui/IconButton';
import Divider from 'material-ui/Divider';

import baseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import {red700, green700, blue400} from 'material-ui/styles/colors';

import DropZone from 'react-dropzone';
import settings from '../../setting.js';

import {Meteor} from 'meteor/meteor';

import crypto from 'crypto';
import {jsRsaSign, KEYUTIL} from "jsrsasign";
import ImageCompressor from 'image-compressor.js';

import repchain from '../api/repchainUtil';

const styles = {
    toolbar: {
        top: 0,
        width: '100%',
        position:'fixed',
    },
    button: {
        padding: 15,
        position: 'relative',
        top: 20,
    },
    uploadButton: {
        verticalAlign: 'middle',
        padding: 15,
    },
    textField: {
        display: 'inline-block',
        width: '85%',
    },
    drop_zone: {
        display: 'inline-block',
        width: 250,
        height: 150,
        borderWidth: 2,
        borderColor: 'rgb(102, 102, 102)',
        borderStyle: 'dashed',
        borderRadius: 5,
    },
    canvas: {
        width: '100%',
        border: 1,
        solid: '#000000',
    }

}

export default class ImageRegister extends Component {

    constructor(props) {
        super(props);
        this.state = {
            ch: 0,
            open: false,
            files: [],
            snackbar_open: false,
            repchainRegisterCopyrightTransactInfo: '',
            repchainRegisterCopyrightTxid: '',

            error_pic_name: '',
            error_pic_author: '',
            error_pic_show:'',

            picture_digital_identity: '',
            picture_name: '',
            picture_file_size: '',
            picture_file_type: '',
            picture_desc: '',
            picture_author: '',
            picture_url: '',
            picture_show:'',

            register_pass: '',
            register_ready: false,
            register_err: '',

            uploadimg: false,
            compressResult: null,
            acceptedFiles: [],
            hashFlag: true,
            uploadstate: '',
        };
    }

    componentWillMount() {
        if (Session.get('curUser') === 'none')
            browserHistory.push('/login');
    }

    componentDidMount(x, y, z) {
        this.setState({cw: window.innerWidth, ch: window.innerHeight});
    }

    onDrop(acceptedFiles, failedFiles) {
        let me = this;
        me.setState({
            output: '正在上传，请稍后...',
            files: [],
        });
        let pos = 0;
        let file = acceptedFiles[pos];
        if (!file) {
            return;
        }
        console.log(JSON.stringify(file))
        // To get picture file hash
        let fr = new FileReader();
        let fd = new FormData();
        let hash = crypto.createHash('sha256');
        let width
        let quality
        let base = (new settings).fileSizeBase
        fr.onload = () => {
            console.log("onload begin")
            hash.update(new Buffer(fr.result));
            me.setState({picture_digital_identity: hash.digest('hex')});
            me.verifyHash(me.state.picture_digital_identity)  // 向repchain查询验证hash值是否上链
            var img = new Image();
            img.src = fr.result;
            img.onload = () => {
                // 5M的处理线
                if (file.size > base) {
                    width = 1024
                    quality = 0.8
                } else {
                    if (img.width > 512) {
                        width = 512
                    } else {
                        width = img.width
                    }
                }
                new ImageCompressor(file, {
                    quality: quality,
                    maxWidth: 1000000,   //为了处理ios
                    maxHeight: 1000000,   // 为了处理ios
                    width: width,
                    convertSize: 3000000,  // 该参数貌似只能处理png 3M
                    success(result) {
                        me.setState({
                            files: acceptedFiles,
                            output: '上传了' + acceptedFiles.length + '张图',
                            compressResult: result,
                        });
                        console.log(me.state.compressResult)
                    },
                    error(e) {
                        console.log(e.message);
                    },
                });
            }

        };
        fr.onerror = () => {
            console.log('file reading encountered error')
        };
        fr.readAsDataURL(file);

        // Fill other fileds
        me.setState({
            picture_file_type: file.type,
            picture_file_size: file.size,
        });

    }

    // Send the compressed image file to server with XMLHttpRequest.
    upload(file) {
        me = this;
        let xhr = new XMLHttpRequest();
        let url = 'http://' + window.location.host + '/uploadPics';
        console.log(url)
        xhr.open('POST', url, true);
        xhr.onload = function (event) {
            console.log(event)
            console.log(event.currentTarget.responseURL);
            me.setState({
                picture_url: event.currentTarget.responseText,
                uploadstate: '上传成功'
            });
        }
        xhr.onerror = function (event) {
            console.log(event)
        }
        xhr.send(file);
    }

    onOpenClick() {
        this.dropzone.open();
    }

    onRegister() {
        let copyright_val = {
            owner_account_address: Session.get('curUser').account_address,
            hash_algorithm: {name: 'sha256', parameter: ''},
            picture_digital_identity: this.state.picture_digital_identity,
            picture_desc: {
                author: this.state.picture_author, name: this.state.picture_name,
                desc: this.state.picture_desc, file_type: this.state.picture_file_type,
                file_size: this.state.picture_file_size, pic_show:this.state.picture_show,
                picture_url: window.location.origin + '/pic?' + this.state.picture_url
            },
        };
        this.setState({open: false,});
        // To register into repchain's data state
        repchain.registerCopyright(this.state.picture_digital_identity, copyright_val, this.state.register_pass,  Session.get('curUser').prv_key_pem_encrypted, Session.get('curUser').account_address, (err, result) => {
            if (err) {
                if (err.message.indexOf('已存在') > -1) {
                    this.setState({
                        repchainRegisterCopyrightTransactInfo: '该文件已登记，请勿重复登记同一文件!',

                    });
                }
                else {
                    this.setState({
                        repchainRegisterCopyrightTransactInfo: err.message,
                    });
                }
                this.setState({repchainRegisterCopyrightTxid: ''})
            }
            else {
                this.setState({
                    repchainRegisterCopyrightTransactInfo: '版权登记请求提交成功，等待上链确认',
                    repchainRegisterCopyrightTxid: result,
                });
            }
            this.setState({snackbar_open: true});
        });
    }

    verifyHash(picture_digital_hash) {
        repchain.verifyHash(picture_digital_hash, (err, result) => {
            console.log(result)
            if(err){
               console.log(err)
            }else if (result.indexOf('未上链') > -1) {
                this.setState({hashFlag: true})
            }else if (result.indexOf('已存在') > -1) {
                this.setState({hashFlag: false})
            }
        })
    }

    getChildContext() {
        return {muiTheme: getMuiTheme(baseTheme)};
    }

    //用户填写信息的界面,从这儿获取用户信息
    renderLists() {
        let w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
        let img_w = w < 250 ? w : 150;
        //dialog对话框上的两个按钮
        //修改：继续提交后当前对话框要清空，回到注册页
        const actions = [
            <FlatButton
                label="确认注册"
                primary={this.state.register_ready}
                disabled={!this.state.register_ready}
                onClick={this.onRegister.bind(this)}
            />,
            <FlatButton
                label="取消注册"
                primary={true}
                keyboardFocused={true}
                onClick={() => this.setState({open: false})}
            />,
        ];

        let credential_type = ['居民身份证', '户口本', '军人证', '武警证', '护照',
            '外国人永久居留证', '港澳居民来往内地通行证', '台湾居民来往通行证'];

        return (
            <div id='image_register' style={{height: this.state.ch, marginTop: 80}}>
                <div id="dropzone">
                    <DropZone ref={(node) => {
                        this.dropzone = node;
                    }} accept='image/*' multiple={false} onDrop={this.onDrop.bind(this)}
                              style={styles.drop_zone}
                    >
                        <div>
                            <br/><br/>
                            <p>+将上传图片拽到此处,<br/>或点击此处选择图片</p>
                        </div>
                    </DropZone>
                </div>

                <div style={{textAlign: 'center'}}>
                    <p className="output">{this.state.output}</p>
                    {this.state.files.map((file, index) => <img className="image" key={index} src={file.preview}/>)}
                </div>

                <TextField
                    hintText="作品名称"
                    floatingLabelText="*作品名称"
                    errorText={this.state.error_pic_name}
                    errorStyle={{marginLeft: '-70%'}}
                    style={styles.textField}
                    onChange={(e, newValue) => {
                        let val = newValue;
                        let err = val == '' ? "作品名称不可为空" : "";
                        this.setState({
                            picture_name: val,
                            error_pic_name: err,
                        });
                    }}
                />
                <TextField
                    hintText="与作品有关的详细信息"
                    floatingLabelText="作品描述"
                    floatingLabelStyle={{marginLeft: '-50%'}}
                    multiLine={true}
                    rows={2}
                    rowsMax={4}
                    style={styles.textField}
                    onChange={(e, newValue) => {
                        let val = newValue;
                        this.setState({
                            picture_desc: val,
                        });
                    }}
                />
                <TextField
                    hintText="作品细节图浏览地址"
                    floatingLabelText="作品展示"
                    floatingLabelStyle={{marginLeft: '-50%'}}
                    multiLine={true}
                    rows={2}
                    rowsMax={4}
                    style={styles.textField}
                    onChange={(e, newValue) => {
                        let val = newValue;
                        this.setState({
                            picture_show: val,
                        });
                    }}
                />
                <TextField
                    hintText="作者名"
                    floatingLabelText="*作者"
                    errorText={this.state.error_pic_author}
                    errorStyle={{marginLeft: '-73%'}}
                    style={styles.textField}
                    onChange={e => {
                        let val = e.target.value;
                        let err = val === '' ? "作者名不可为空" : '';
                        this.setState({
                            picture_author: val,
                            error_pic_author: err,
                        });
                    }}
                />
                <TextField
                    name="owner"
                    disabled={true}
                    multiLine={true}
                    defaultValue={'版权所有者：' + Session.get('curUser').name}
                    style={styles.textField}
                />
                <TextField
                    name="phone"
                    disabled={true}
                    defaultValue={'登记手机号: ' + Session.get('curUser').phone}
                    style={styles.textField}
                />
                <RaisedButton
                    label="提交"
                    primary={this.state.picture_name != '' && this.state.picture_author != '' && this.state.picture_digital_identity != ''}
                    disabled={this.state.picture_name == '' || this.state.picture_author == '' || this.state.picture_digital_identity == ''}
                    fullWidth={true}
                    style={styles.button}
                    onClick={() => {
                        if (this.state.hashFlag) {
                            this.upload(this.state.compressResult)
                            this.setState({open: true})
                        } else {
                            this.setState({snackbar_open: true});
                            this.setState({repchainRegisterCopyrightTransactInfo: '该图片已上链，重新提交'})
                        }
                    }}
                />
                <Dialog
                    title="版权登记提醒"
                    actions={actions}
                    modal={false}
                    open={this.state.open}
                    autoScrollBodyContent={true}
                    onRequestClose={() => this.setState({open: false})}
                >
                    <Divider style={{border: '1px dashed', marginTop: 2}}/>
                    请确保所填写版权登记信息的真实性:<br/>
                    1. 一旦提交注册成功，区块链网络中将永久保存您的版权主张记录，且无法删除。您的版权登记记录将可作为版权主张证据;<br/>
                    2. 若您对非自己所有版权的图片进行版权登记，您的登记记录也将会成为您侵权行为的证据被永久保存于区块链网络，且无法删除。
                    <Divider style={{border: '1px dashed', marginBottom: 30}}/>
                    <p style={{color: red700}}>*输入私钥密码:</p>
                    <TextField
                        name="user_pass"
                        type='password'
                        floatingLabelText='私钥密码'
                        floatingLabelStyle={{color: blue400}}
                        errorText={this.state.register_err}
                        hintText='输入密码'
                        onChange={(e, newValue) => {
                            if (newValue === '')
                                this.setState({register_ready: false, register_pass: newValue, register_err: '密码不可为空'});
                            else
                                this.setState({register_ready: true, register_pass: newValue, register_err: ''});
                        }}
                    />
                </Dialog>
            </div>
        );
    }

    renderChip() {
        let avatar_color = this.state.repchainRegisterCopyrightTxid == '' ? red700 : green700;
        let avatar_icon = this.state.repchainRegisterCopyrightTxid == '' ? <SvgIconErr/> : <SvgIconCheck/>;
        return (
            <Chip style={{top: 25,}} onClick={() => {
                this.setState({snackbar_open: false});
                browserHistory.push('tab1');
            }}>
                <Avatar color={avatar_color} icon={avatar_icon}/>
                {this.state.repchainRegisterCopyrightTransactInfo}
            </Chip>
        );
    }

    render() {
        return (
            <div>
                <AppBar
                    style={styles.toolbar}
                    title={"登记作品"}
                    titleStyle={{overflow: 'visible'}}
                    iconElementLeft={
                        <IconButton
                            iconStyle={{width: 48, height: 48}}
                            style={{padding: 0}}
                            onTouchTap={(e) => browserHistory.push('/tab1')}
                        >
                            <SvgIconLeftNavi/>
                        </IconButton>}
                >
                </AppBar>
                {this.renderLists()}

                <Snackbar
                    open={this.state.snackbar_open}
                    message={this.renderChip()}
                    autoHideDuration={2000}
                    bodyStyle={{backgroundColor: 'rgba(47,47,47,0.7)', height: 'auto', textAlign: 'center'}}
                    contentStyle={{height: 80, display: 'inline-block'}}
                    onRequestClose={(reason) => {
                        this.setState({snackbar_open: false});
                        browserHistory.push('tab1');
                    }}
                />
            </div>
        );
    }
}

ImageRegister.childContextTypes = {
    muiTheme: React.PropTypes.object.isRequired,
};